<?php
namespace AuctionCore\Other;

use AuctionCore\Model\AuCarOwner;

//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                         |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: liugohua@clcw.com.cn  Blog:http://blog.sina.com.cn/saverneo        |
// +------------------------------------------------------------------------+
//


/**
 * 车主列表
 * @author       Eric Lee
 */
class CouponList extends \AuctionCore\System\ListBase
{
    /**
     * 获取列表结果
     * @param    int $page_number 每页条数
     * @param    int $page 页码
     * @return   Array
     */
    public function get($size, $page)
    {
        $m = new AuCarOwner();
        $m->where($this->condition);
        $m->field($this->fields);
        $m->order($this->order_by);
        //dump($m,true,null,false);
        if ($size < 1) $size = 1;
        if ($page < 2) $page = 1;
        $offset = ($page - 1) * $size;
        $m->limit($offset, $size);
        $ls = $m->select();
        return $ls;
    }

    public function count()
    {

    }

    /**
     * 获取代金券列表
     * @param integer $page
     * @param integer $size
     * @param array $paramer
     * @return multitype:array(list,total)
     */
    public function getList($page = 1, $size = 10, $paramer)
    {
        $map = array();
        //类型
        if ($paramer['type']) {
            $map['c.coupon_type_id'] = array('eq', $paramer['type']);
        }
        //使用状态
        if ($paramer['use_status']) {
            switch ($paramer['use_status']) {
                case '1'://未使用
                    $map['dc.use_status'] = array('eq', '0');
                    $map['c.end_date'] = array('egt', date('Y-m-d'));
                    break;
                case '2'://已使用
                    $map['dc.use_status'] = array('eq', '1');
                    break;
                case '3'://已过期
                    $map['dc.use_status'] = array('neq', '1');
                    $map['c.end_date'] = array('lt', date('Y-m-d'));
                    break;
            }
        }
        //发放状态
        if ($paramer['status']) {
            switch ($paramer['status']) {
                case '1'://待发放
                    $map['c.assign_status'] = array('eq', '0');
                    $map['c.end_date'] = array('egt', date('Y-m-d'));
                    break;
                case '2'://已发放
                    $map['c.assign_status'] = array('eq', '1');
                    break;
                case '3' ://已过期
                    $map['c.assign_status'] = array('neq', '1');
                    $map['c.end_date'] = array('lt', date('Y-m-d'));
                    break;
            }
        }
        //关键字
        if ($paramer['keyword']) {
            $where = array();
            $where['c.coupon_no'] = array('eq', $paramer['keyword']);
            $where['u.user_name'] = array('like', '%' . $paramer['keyword'] . '%');
            $where['_logic'] = 'OR';
            $map['_complex'] = $where;
        }

        $prefix = C('DB_PREFIX');
        $cols = 'u.user_name,c.coupon_no,cd.dealer_id,cd.fullname,ct.type_name,ct.amount,c.assign_status,dc.use_status,c.start_date,c.end_date';
        $total = M('coupon')->alias('c')->join("LEFT JOIN " . C('DB_PREFIX') . "coupon_type ct ON c.coupon_type_id=ct.coupon_type_id")
            ->join("LEFT JOIN " . C('DB_PREFIX') . "dealer_coupon dc ON dc.coupon_id=c.coupon_id")
            ->join("LEFT JOIN " . C('DB_PREFIX') . "car_dealer cd ON cd.dealer_id=dc.dealer_id")
            ->join("LEFT JOIN " . $prefix . "dealer_user as du ON cd.dealer_id=du.dealer_id")
            ->join("LEFT JOIN " . $prefix . "user as u ON u.uid=du.uid")
            ->where($map)->count();

        $list = M('coupon')->alias('c')->field($cols)
            ->join("LEFT JOIN " . $prefix . "coupon_type ct ON c.coupon_type_id=ct.coupon_type_id")
            ->join("LEFT JOIN " . $prefix . "dealer_coupon dc ON dc.coupon_id=c.coupon_id")
            ->join("LEFT JOIN " . $prefix . "car_dealer cd ON cd.dealer_id=dc.dealer_id")
            ->join("LEFT JOIN " . $prefix . "dealer_user as du ON cd.dealer_id=du.dealer_id")
            ->join("LEFT JOIN " . $prefix . "user as u ON u.uid=du.uid")
            ->where($map)->limit($size)->page($page)->order("c.coupon_id desc")->select();
        //echo M()->getLastSql();
        foreach ($list as $key => $val) {
            $list[$key]['start_date'] = date('Y.m.d', strtotime($val['start_date']));
            $list[$key]['end_date'] = date('Y.m.d', strtotime($val['end_date']));
        }
        //echo M()->getLastSql();
        $result = array(
            'list' => $list,
            'total' => $total
        );
        return $result;
    }

    /**
     * 获取车商在订单中使用代金券的总额
     * @param unknown $dealer_id
     * @param unknown $order_id
     * @return \Think\mixed
     * @author an
     */
    public function getSumCouponCost($dealer_id, $order_id)
    {
        $Coupon = M("coupon_log");
        $map = array();
        $map['dealer_id'] = array('eq',$dealer_id);
        $map['order_id'] = array('eq',$order_id);
        $map['occur_type'] = array('eq',1);
        return $Coupon->where($map)->sum('occur_money');
    }

    /**
     * 获取未使用的代金券总额
     * @param unknown $dealer_id
     * @param unknown $order_id
     * @return \Think\mixed
     * @author an
     */
    public function getSumCouponAvailable($dealer_id)
    {
        $map = array();
        $map['dc.dealer_id'] = array('eq',$dealer_id);
        $map['dc.use_status'] = array('eq', '0');
        $map['c.end_date'] = array('egt', date('Y-m-d'));

        $sum = M('coupon')->alias('c')->join("LEFT JOIN " . C('DB_PREFIX') . "coupon_type ct ON c.coupon_type_id=ct.coupon_type_id")
            ->join("LEFT JOIN " . C('DB_PREFIX') . "dealer_coupon dc ON dc.coupon_id=c.coupon_id")->sum('ct.amount');

        return $sum;
    }
    /**
     * 获取未使用的代金券总额
     * @param unknown $dealer_id
     * @param unknown $order_id
     * @return \Think\mixed
     * @author an
     */
    public function get_coupon_list($dealer_id)
    {
        $map = array();
        $map['dc.dealer_id'] = array('eq', $dealer_id);
        $map['dc.use_status'] = array('eq', '0');
        $map['dc.start_date'] = array('elt', date('Y-m-d'));
        $map['dc.end_date'] = array('egt', date('Y-m-d'));
        $prefix = C("DB_PREFIX");
        $res = M("dealer_coupon")->alias("dc")->field("dc.*,o.order_no,ct.type_name,a.type")
            ->join(" left join ".$prefix."coupon_type as ct on dc.coupon_type_id = ct.coupon_type_id")
            ->join(" left join ".$prefix."activity as a on a.aid = ct.a_id")
            ->join(" left join ".$prefix."lottery_coupon as lc on lc.coupon_id = dc.coupon_id")
            ->join(" left join ".$prefix."scratch_card as sc on sc.cid = lc.card_id")
            ->join(" left join ".$prefix."order as o on o.order_id = sc.order_id")
            ->where($map)->order("end_date")->select();
        return $res;
    }
    /**
     * 默认代金券排序算法
     * @author niuzhixin
     */
    public function pase_coupon($arrUsers){
        foreach ($arrUsers as $key => $row) {
            $amount[$key] = $row['amount'];
            $end_date[$key]  = $row['end_date'];
        }
        array_multisort($amount, SORT_DESC,SORT_NUMERIC, $end_date, SORT_ASC, $arrUsers);
        //相同id临时放到一起
        $tem = array();
        foreach ($arrUsers as $value) {
            $tem[$value['amount']][] = $value;
        }
        //输出最终结果
        $result = array();
        foreach ($tem as $sub_arr) {
            foreach ($sub_arr as $value) {
                $result[] = $value;
            }
        }
        return $result;
    }
    /**
     * 获取默认可以使用的代金券coupon_id
     * @author niuzhixin
     */
    public function get_coupon_id($arr,$amount){
        // 最多可使用代金券金额
        $maxV = $amount;
        $info = array();
        foreach($arr as $k => $v){
            $info[] = $v['amount'];
        }
        // 相应类型代金券的数量
        $coupon_num = array_count_values($info);
        $i = 0;
        foreach($coupon_num as $v){
            $couponTypeCount[$i] =$v;
            $i++;
        }
        // 代金券的类型（额度）
        $couponType = array_unique($info);
        rsort($couponType);
        // 代金券种类数量
        $count = count($couponType);
        // 一类代金券最少过期时间（一组代金券中的最小值）
        $couponTimeout = array();
        foreach($couponType as $k){
            foreach($arr as $key => $value){
                if($value['amount'] == $k){
                    $oo_couponTimeout[$k][] = $value['end_date'];
                }
            }
        }
        foreach($oo_couponTimeout as $k => $v){
            $old_couponTimeout[] = min($v);
        }
        foreach($old_couponTimeout as $k){
            $couponTimeout[] = strtotime($k);
        }
        $result = $this->main($maxV,$count,$couponType,$couponTypeCount,$couponTimeout);
        $confirm_id = $this->confirm_coupon_id($arr,$result);
        return $confirm_id;
    }
    //计算确定的代金券id
    public function confirm_coupon_id($arr,$result){
        $info = array();
        foreach($result as $key => $value){
            $i = 0;
            foreach($arr as $k => $v){
                if($v['amount'] == $key && $i<$value){
                    $info[] = $v['coupon_id'];
                    $i++;
                }
            }
        }
        return $info;
    }
    //背包算法
    public function main($maxV,$count,$couponType,$couponTypeCount,$couponTimeout) {

        // 最多可使用代金券金额
        //$maxV = 500;
        // 代金券种类数量
        //$count = 4;
        // 代金券的类型（额度）
        //$couponType = array(100, 200, 500, 1000);
        // 相应类型代金券的数量
        //$couponTypeCount = array(6, 3, 1, 1);
        // 一类代金券最少过期时间（一组代金券中的最小值）
        //$coutponTimeout = array(3, 2, 1, 5);
        // 计算最优解
        $last = $this->computerCoupon($maxV, $count, $couponType, $couponTypeCount, $couponTimeout);
        $resMoney = $last[0];
        $resTimeout = $last[1];
        $resCount = $last[2];
        $resPre = $last[3];
        /*echo "代金券类型","<br/>";
        for($i = 0; $i < $count; $i ++) {
            echo $couponType[$i]."元\t" .$couponTypeCount[$i]."张\t".$couponTimeout[$i]."天\t",'<br>';
        }
        echo "可使用:\t\t" .$maxV."元",'<br>';
        echo "最多使用:\t".$resMoney[$maxV]."元",'<br>';
        echo "过期时间:\t".$resTimeout[$maxV]."天",'<br>';
        echo "使用数量:\t".$resCount[$maxV]."张",'<br>';
        echo "使用规则:\t";*/
        $res = array();
        $tempV = $maxV;
        for($i = $count - 1; $i >= 0; $i --) {
            $res[$couponType[$i]] = $resPre[$i][$tempV];
            //echo "面额".$couponType[$i]."元代金券，使用".$resPre[$i][$tempV]."张",'<br>';
            $tempV -= $couponType[$i] * $resPre[$i][$tempV];
        }
        return $res;
    }
    //背包算法 核心
    public function computerCoupon($maxV, $count, $couponType, $couponTypeCount,$couponTimeout) {

        // 初始化数据
        for($v = 0; $v <= $maxV; $v ++) {
            $resMoney[$v] = 0;
            $resTimeout[$v] = 2079312000; // 代表10000天的过期时间
            $resCount[$v] = 0;

            for($i = 0; $i < $count; $i ++) {
                $resPre[$i][$v] = 0;
            }
        }

        for($i = 0; $i < $count; $i ++) {
            $value = $couponType[$i];           // 第i种代金券的金额
            $number = $couponTypeCount[$i];     // 第i种代金券的数量
            $minTimeout = $couponTimeout[$i];  // 第i种代金券最少过期时间
            for($v = $maxV; $v >= $value; $v --) {
                for($k = 1; $k <= $number; $k ++) {
                    if($v < $k * $value) break;
                    $valueK = $resMoney[$v - $k * $value] + $k * $value; // 使用k个第i中代金券的最大值
                    $minTimeoutK = min($resTimeout[$v - $k * $value], $minTimeout); // 使用k个第i中代金券的最少过期时间
                    $numberK = $resCount[$v - $k * $value] + $k; // 使用k个第i中代金券的最少数量
                    if($resMoney[$v] < $valueK) {
                        // 更新最大金额、最小过期时间、使用最少张数
                        $resMoney[$v] = $valueK;
                        $resTimeout[$v] = $minTimeoutK;
                        $resCount[$v] = $numberK;
                        $resPre[$i][$v] = $k;
                    } else if($resMoney[$v] == $valueK) {
                        // 最大值相等，考虑最小过期时间
                        if($resTimeout[$v] > $minTimeoutK) {
                            // 更新最小过期时间、使用最少张数
                            $resTimeout[$v] = $minTimeoutK;
                            $resCount[$v] = $numberK;
                            $resPre[$i][$v] = $k;
                        } else if($resTimeout[$v] == $minTimeoutK) {
                            // 最小过期时间相等，考虑使用最少张数
                            if($resCount[$v] > $numberK) {
                                // 更新使用最少张数
                                $resCount[$v] = $numberK;
                                $resPre[$i][$v] = $k;
                            }
                        }
                    }
                }
            }
        }
        return [
            $resMoney ,   // 价格
            $resTimeout,// 过期时间
            $resCount,   // 最少数量
            $resPre,// 每种代金券使用的张数
        ];
    }
    /**
     * 获取确认使用代金券的面额
     * @author niuzhixin
     */
    public function get_confirm_coupon($coupon_ids){
        $coupon_id = explode(',',$coupon_ids);
        $map = array();
        $map['dc.coupon_id'] = array('in',$coupon_id);
        $prefix = C("DB_PREFIX");
        $res = M("dealer_coupon")->alias("dc")->field("dc.*,o.order_no,ct.type_name,a.type")
            ->join(" left join ".$prefix."coupon_type as ct on dc.coupon_type_id = ct.coupon_type_id")
            ->join(" left join ".$prefix."activity as a on a.aid = ct.a_id")
            ->join(" left join ".$prefix."lottery_coupon as lc on lc.coupon_id = dc.coupon_id")
            ->join(" left join ".$prefix."scratch_card as sc on sc.cid = lc.card_id")
            ->join(" left join ".$prefix."order as o on o.order_id = sc.order_id")
            ->where($map)->order("end_date")->select();
        $total = 0;
        foreach($res as $k => $v){
            $total += $v['amount'];
        }
        return $total;
    }
}